<?php
include_once("../../untils/conn.php");
// mysqli_query($con, "set names utf8");
// 获取要更新的商品ID和渠道名称
$id = $_POST["id"];
$channel_name = $_POST["channel_name"];

// 查询渠道名称对应的渠道ID
$sql = "SELECT channel_id FROM channel WHERE channel_name = '$channel_name'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);
$channel_id = $row["channel_id"];



// 查询商品的已有渠道数
$sql = "SELECT channel, channel_one, channel_two FROM list WHERE id = '$id'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($result);

// 判断要写入的渠道字段
if ($row["channel"] == null) {
    $field = "channel";
} elseif ($row["channel_one"] == null) {
    $field = "channel_one";
} elseif ($row["channel_two"] == null) {
    $field = "channel_two";
} else {
    // 商品已有三个渠道，加入失败
    // echo "加入失败，每个商品只能添加三个渠道";
    echo ("<script>alert('加入失败，每个商品只能添加三个渠道');history.back();</script>");
    exit;
}

// 更新商品的渠道字段
$sql = "UPDATE list SET $field = '$channel_id' WHERE id = '$id'";
if(mysqli_query($con, $sql)) {
    // 更新成功，弹出加入成功提示
    // echo "加入成功";
    echo ("<script>alert('加入渠道成功');history.back();</script>");
} else {
    // 更新失败，提示加入失败
    echo "加入失败，请稍后重试";
     echo ("<script>alert('加入渠道失败');history.back();</script>");
}
